<!doctype html>
<html lang="en">
  <head>
    <title>Canvas</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
      body,
      html {
        padding: 0;
        margin: 0;
      }
      #canvas {
        margin: 10px;
        box-shadow: 4px 4px 12px rgba(0, 0, 0, 0.5);
      }
    </style>
  </head>
  <body>
    <canvas id="canvas"></canvas>

    <script src="utils.js"></script>
    <script>
      const canvas = C.$("#canvas");
      const ctx = canvas.getContext("2d");

      const W = (canvas.width = 600);
      const H = (canvas.height = 400);

      const mouse = C.getOffset(canvas);

      canvas.onmousemove = () => {
        ctx.clearRect(0, 0, W, H);

        drawSystem();

        // 鼠标距离坐标系中心点(0, 0)的差值
        const dx = mouse.x - W / 2;
        const dy = mouse.y - H / 2;
        // const angle = (Math.atan(dy / dx) * 180) / Math.PI;
        const angle = (Math.atan2(dy, dx) * 180) / Math.PI;

        ctx.beginPath();
        ctx.lineTo(W / 2, H / 2);
        ctx.lineTo(mouse.x, mouse.y);
        ctx.stroke();
        ctx.fillText(angle, mouse.x, mouse.y);
      };

      function drawSystem() {
        ctx.save();
        ctx.lineWidth = 1;

        ctx.beginPath();

        // X 轴
        ctx.moveTo(0, H / 2); // 起始点
        ctx.lineTo(W, H / 2); // 结束点

        // Y 轴
        ctx.moveTo(W / 2, 0); // 起始点
        ctx.lineTo(W / 2, H); // 结束点

        ctx.stroke(); // 描边

        ctx.restore();
      }

      drawSystem();
    </script>
  </body>
</html>
